package com.triones.yjj.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.triones.yjj.entity.MemberWithdrawDO;
import com.triones.yjj.entity.OrderTradeRecordDO;
import com.triones.yjj.entity.StaffDO;
import com.triones.yjj.entity.bo.MemberWithdrawParams;
import com.triones.yjj.entity.bo.RemainderListParams;
import com.triones.yjj.entity.bo.WaitSettlementListParams;
import com.triones.yjj.entity.bo.WithdrawalListParams;
import com.triones.yjj.entity.vo.MemberWithdrawListVO;
import com.triones.yjj.entity.vo.RemainderDetailListVO;
import com.triones.yjj.entity.vo.WaitSettlementRecordVO;
import com.triones.yjj.entity.vo.WithdrawalRecordVO;
import com.triones.yjj.mapper.OrderMapper;
import com.triones.yjj.mapper.OrderTradeRecordMapper;
import com.triones.yjj.mapper.WithdrawalRecordMapper;
import com.triones.yjj.service.OrderTradeService;
import com.xkcoding.http.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 订单交易业务实现 service 业务实现
 *
 * @Author: triones
 */
@Service
@RequiredArgsConstructor
public class OrderTradeServiceImpl implements OrderTradeService {

    private final OrderMapper orderMapper;

    private final OrderTradeRecordMapper orderTradeRecordMapper;

    private final WithdrawalRecordMapper withdrawalRecordMapper;

    private final SysUserMapper baseMapper;

    @Override
    public TableDataInfo<RemainderDetailListVO> remainderPageList(RemainderListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<StaffDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getOrderNo()),"b.order_no",params.getOrderNo());
        wrapper.eq(ObjectUtil.isNotNull(params.getOrderSource()),"b.order_source",params.getOrderSource());
        wrapper.eq(ObjectUtil.isNotNull(params.getActivityId()),"b.activity_id",params.getActivityId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getGroupPurchaseGoods()),"f.goods_name",params.getGroupPurchaseGoods());
        wrapper.and(ObjectUtil.isNotEmpty(params.getTraders()),qw -> {
            qw.eq("d.id",params.getTraders()).or()
                .like("d.nickname",params.getTraders());
        });
        wrapper.like(ObjectUtil.isNotEmpty(params.getFundType()),"a.fund_type",params.getFundType());
        if (params.getDateRange() != null && params.getDateRange().size() > 0) {
            wrapper.between("a.create_time",params.getDateRange().get(0),params.getDateRange().get(1));
        }
        wrapper.orderByDesc("a.create_time");
        Page<RemainderDetailListVO> result = orderTradeRecordMapper.remainderPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<WithdrawalRecordVO> withdrawalPageList(WithdrawalListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<StaffDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getWithdrawalNo()),"a.withdrawal_no",params.getWithdrawalNo());
        wrapper.like(ObjectUtil.isNotEmpty(params.getNickname()),"b.nickname",params.getNickname());
        wrapper.eq(ObjectUtil.isNotNull(params.getStatus()) && params.getStatus() != 0,"a.status",params.getStatus());
        if (params.getCreateTimeRange() != null && params.getCreateTimeRange().size() > 0) {
            wrapper.between("a.create_time",params.getCreateTimeRange().get(0),params.getCreateTimeRange().get(1));
        }
        if (params.getReachTimeRange() != null && params.getReachTimeRange().size() > 0) {
            wrapper.between("a.reach_time",params.getReachTimeRange().get(0),params.getReachTimeRange().get(1));
        }
        wrapper.orderByDesc("a.reach_time","a.create_time");
        Page<WithdrawalRecordVO> result = orderTradeRecordMapper.withdrawalPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<WaitSettlementRecordVO> waitSettlementDetailList(WaitSettlementListParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<OrderTradeRecordDO> wrapper = Wrappers.query();
        wrapper.eq("a.user_id",loginUser.getUserId()).eq("b.status",2).eq("a.settlement_status",1);
        wrapper.like(ObjectUtil.isNotEmpty(params.getOrderNo()),"b.order_no",params.getOrderNo());
        wrapper.like(ObjectUtil.isNotNull(params.getOrderSource()),"b.order_source",params.getOrderSource());
        wrapper.like(ObjectUtil.isNotNull(params.getActivityId()),"b.activity_id",params.getActivityId());
        wrapper.like(ObjectUtil.isNotEmpty(params.getGroupPurchaseGoods()),"c.goods_name",params.getGroupPurchaseGoods());
        wrapper.eq(ObjectUtil.isNotEmpty(params.getTraders()),"bw.id",params.getTraders())
            .or()
            .like(ObjectUtil.isNotEmpty(params.getTraders()),"bw.nickname",params.getTraders());
        wrapper.like(ObjectUtil.isNotEmpty(params.getFundType()),"a.fund_type",params.getFundType());
        if (params.getDateRange() != null && params.getDateRange().size() > 0) {
            wrapper.between("a.create_time",params.getDateRange().get(0),params.getDateRange().get(1));
        }
        wrapper.orderByDesc("a.create_time");
        Page<WaitSettlementRecordVO> result = orderTradeRecordMapper.waitSettlementDetailList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }

    @Override
    public Map stats() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        Map map = new HashMap();
        /**
         * 可提现金额
         */
        SysUser sysUser = baseMapper.selectVoById(loginUser.getUserId());
        if (sysUser == null) {
            throw new ServiceException("没有查询到商户信息");
        }
        /**
         * 可提现金额
         */
        map.put("walletAmount", Convert.toBigDecimal(sysUser.getWalletAmount(),BigDecimal.ZERO));
        /**
         * 待提现金额
         */
        map.put("waitSettlementAmount", Convert.toBigDecimal(sysUser.getWaitSettlementAmount(),BigDecimal.ZERO));
        /**
         * 待结算金额
         */
        String waitSettlementTotal = orderTradeRecordMapper.waitSettlementTotal(loginUser.getUserId());
        map.put("waitSettlementTotal", Convert.toBigDecimal(waitSettlementTotal,BigDecimal.ZERO));
        /**
         * 成功提现金额
         */
        String alreadyWithdrawalTotal = orderTradeRecordMapper.alreadyWithdrawalTotal(loginUser.getUserId());
        map.put("alreadyWithdrawalTotal", Convert.toBigDecimal(alreadyWithdrawalTotal,BigDecimal.ZERO));
        /**
         * 累计分销佣金
         */
        String inviteDeductionTotal = orderTradeRecordMapper.inviteDeductionTotal(loginUser.getUserId());
        map.put("inviteDeductionTotal", Convert.toBigDecimal(inviteDeductionTotal,BigDecimal.ZERO));
        /**
         * 累计手续费
         */
        String commissionTotal = orderTradeRecordMapper.commissionTotal(loginUser.getUserId());
        map.put("commissionTotal", Convert.toBigDecimal(commissionTotal,BigDecimal.ZERO));
        /**
         * 累计提现中
         */
        String inProgressWithdrawalTotal = withdrawalRecordMapper.inProgressWithdrawalTotal(loginUser.getUserId());
        map.put("inProgressWithdrawalTotal", Convert.toBigDecimal(inProgressWithdrawalTotal,BigDecimal.ZERO));
        return map;
    }

    @Override
    public TableDataInfo<MemberWithdrawListVO> memberWithdrawPageList(MemberWithdrawParams params, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException("当前用户退出登录!");
        }
        QueryWrapper<MemberWithdrawDO> wrapper = Wrappers.query();
        wrapper.eq("tm.user_id",loginUser.getUserId());
        wrapper.eq(ObjectUtil.isNotNull(params.getState()),"tmw.state",params.getState());
        wrapper.like(ObjectUtil.isNotEmpty(params.getNickname()),"twu.nickname",params.getNickname()).or()
            .like(ObjectUtil.isNotEmpty(params.getNickname()),"twu.id",params.getNickname());
        Page<MemberWithdrawListVO> result = orderTradeRecordMapper.memberWithdrawPageList(pageQuery.build(), wrapper);
        return TableDataInfo.build(result);
    }
}
